<template>
  <div>
    <div>
      <i-menu id="menu_contain" mode="horizontal" theme="light" active-name="1" @on-select="selectMenu">
        <img id="logo_img" src="./assets/recruit.png">
        <MenuItem class="menu_item" :key="item.name" v-for="item in viewRoutes" v-if="item.menu&&item.menu.level==1" :name="item.name">
          <Icon :type="item.menu.icon"></Icon>
          {{item.label}}
        </MenuItem>
        <Submenu class="menu_item" :key="item.name" v-for="item in viewRoutes" v-if="item.menu&&item.menu.level==2" :name="item.name">
          <template slot="title">
            <Icon :type="item.menu.icon"></Icon>
            {{item.label}}
          </template>
          <MenuItem :key="i.name" v-for="i in getSubMenu(item.menu.child)" :name="i.name">
            {{i.label}}
          </MenuItem>
        </Submenu>
      </i-menu>
    </div>

    <Modal v-model="loginModal" width="360" :closable="false" :mask-closable="true">
      <div>
        <div style="margin:10px;text-align:center">
          <img :src="require('@/assets/logo.jpeg')" alt="logo" height="50">
        </div>
        <Form ref="loginFormValidate" :model="loginFormValidate" :rules="loginRuleValidate">
          <Form-item prop="phoneNum">
            <Input v-model="loginFormValidate.phoneNum" type="text" placeholder="请输入手机号"/>
          </Form-item>
          <Form-item prop="password">
            <Input v-model="loginFormValidate.password" type="password" placeholder="请输入密码" @keyup.native.enter="handleLoginSubmit('loginFormValidate')"/>
          </Form-item>

          <Row>
            <i-col span="12">
              <Checkbox-group v-model="loginFormValidate.remember">
                <Checkbox label="记住我"/>
              </Checkbox-group>
            </i-col>
            <i-col span="12">
              <a style="float:right" @click="toRegister">新用户注册</a>
            </i-col>
          </Row>

        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" size="large" long @click="handleLoginSubmit('loginFormValidate')">登录</Button>
        <small style="text-align: center; display:block; margin-top: 5px">@copyright by DtDream</small>
      </div>
    </Modal>


    <Modal v-model="registerModal" width="360" :closable="false" :mask-closable="true">
      <div>
        <div style="margin:10px; text-align:center">
          <img :src="require('@/assets/logo.jpeg')" alt="logo" height="50">
        </div>
        <Form ref="registerFormValidate" :model="registerFormValidate" :rules="registerRuleValidate">
          <Form-item prop="phoneNum">
            <Input v-model="registerFormValidate.phoneNum" type="text" placeholder="请输入手机号"/>
          </Form-item>
          <Form-item prop="password1">
            <Input v-model="registerFormValidate.password1" type="password" placeholder="请输入密码"/>
          </Form-item>
          <Form-item prop="password2">
            <Input v-model="registerFormValidate.password2" type="password" placeholder="请再输入密码"/>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" size="large" long @click="handleRegisterSubmit('registerFormValidate')">注册</Button>
        <small style="text-align: center; display:block; margin-top: 5px">@copyright by DtDream</small>
      </div>
    </Modal>

    <div :style=content_height class="content">
      <router-view/>
    </div>

    <div id="pageFooter">
      <span>2017-2020 &copy; 杭州数梦工场科技有限公司</span>
    </div>

  </div>


</template>

<script>

  import { mapGetters } from 'vuex'
  import routes from './router/routes'
  import authApi from './api/axios/authApi'
  import userRecruitApi from './api/axios/userRecruitApi'


  export default {
  data () {
    return {
      layoutMode: false,
      loginModal: false,
      registerModal: false,
      viewRoutes: routes.routes,
      content_height: 'min-height:' + (window.innerHeight-130) + 'px;',
      loginFormValidate: {
        phoneNum: '',
        password: '',
        remember: []
      },
      loginRuleValidate: {
        phoneNum: [
          {required: true, message: '手机号错误',pattern: /^1[34578]\d{9}$/, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ]
      },
      registerFormValidate: {
        phoneNum: '',
        password1: '',
        password2: '',
      },
      registerRuleValidate: {
        phoneNum: [
          {required: true, message: '手机号错误',pattern: /^1[34578]\d{9}$/, trigger: 'blur'}
        ],
        password1: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {type: 'string', min: 6, message: '密码不能少于6位', trigger: 'blur'}
        ],
        password2: [
          {validator: this.validatePassword, trigger: 'blur'}
        ]
      }
    }
  },
  computed : {
    ...mapGetters({loginSessionCache: 'auth/getLoginSessionCache'}),
    ...mapGetters({loginSessionState: 'auth/getLoginSessionState'}),
    ...mapGetters({failNumState: 'auth/getFailNumState'}),
    ...mapGetters({getUserId: 'auth/getUserId'})
//    loginSessionCache () {
//      return this.$store.getters.getLoginSessionCache
//    }
  },
  methods:{
    selectMenu (name) {

      for (let value of this.viewRoutes) {
        if (name === 'sign_in'){
          this.loginModal = true;
          break;
        }

        if (name === 'sign_up'){
          this.registerModal = true;
          break;
        }

        if (name === 'sign_out'){
          this.$store.commit('auth/removeSessionMutation');
          this.$Message.success('退出成功');
          this.$router.push('/social_recruit');
          break;
        }

        if (name === value.name){
          this.$router.push(value.path);
          break;
        }
      }
    },
    getSubMenu (arr) {
      let result = [];
      const grep = this.layoutMode ? 'member' : 'visitor';
      for (let i of arr) {
        for (let f of this.viewRoutes) {
          if (i === f.name && grep === f.grep){
            result.push(f);
          }
        }
      }
      return result;
    },
    handleLoginSubmit (loginFormValidate){
      let that = this;
      this.$refs[loginFormValidate].validate((valid) => {
        if (valid) {

          authApi.login({
            phoneNum: this.loginFormValidate.phoneNum,
            password: this.loginFormValidate.password
          },{
            success (res) {
              if (res.data.status === 200) {

                let data = {online: true, token: res.data.data.token, name: res.data.data.name, id: res.data.data.id};
                that.$store.commit('auth/updateSessionMutation',data);

                if (that.loginFormValidate.remember.length > 0){
                  that.$store.commit('auth/rememberMutation');
                }

              }else {
                let data = {online: false, token: "", name: "", id: 0};
                that.$store.commit('auth/updateSessionMutation',data);
              }
            }
          });

//            this.$store.dispatch('auth/login', this.loginFormValidate);
//            this.$refs[loginFormValidate].resetFields();
        } else {
          this.$Message.error('请重新登录');
        }
      });

    },
    handleRegisterSubmit (registerFormValidate){
      let that = this;
      this.$refs[registerFormValidate].validate((valid) => {
        if (valid) {

          authApi.register({
            phoneNum: this.registerFormValidate.phoneNum,
            password: this.registerFormValidate.password1
          },{
            success (res) {
              if (res.data.status === 200) {
                that.$Message.success('注册成功');
                that.$refs[registerFormValidate].resetFields();
                that.registerModal= false;

                userRecruitApi.createResume({
                  userId: that.getUserId,
                },{
                  success (res) {
                    if (res.data.status === 200) {
                      console.log("简历初始化成功!");
                    }else {
                      console.log("createResume 请求失败：" + res.data);
                    }
                  }
                });

              }else {
                that.$Message.error('注册失败');
              }
            }
          });
        } else {
          this.$Message.error('输入的信息格式不正确');
        }
      });

    },
    toRegister (){
      this.loginModal= false;
      this.registerModal= true;
    },
    validatePassword (rule, value, callback){
      if (value === '') {
        callback(new Error('密码不能为空'))
      } else if (value !== this.registerFormValidate.password1) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    },
    initViewState (){
      this.layoutMode = this.loginSessionCache.online;
      this.$router.push('/social_recruit');
    }
  },watch: {
    loginSessionState: function (newLoginSession) {
      if (newLoginSession.online){
        this.$Message.success('登录成功');
        this.layoutMode = true;
        this.loginModal = false;
      }else {
        this.layoutMode = false;
      }
    },
    failNumState: function (newFailNum) {
      this.layoutMode = false;
      this.$Message.error('账号或密码错误');
    }
  },
  mounted(){

  },
  created () {
    this.initViewState();
  }
}
</script>

<style>

  #menu_contain {
    display: flex;
    align-items: center;
    height: 80px;
  }

  .menu_item {
    display: flex;
    align-items: center;
    font-size: 20px;
  }

  #logo_img {
    /*float: left;*/
    height: 60px;
    width: 60px;
    margin-left:40px;
    margin-right:20px;
  }

  #pageFooter {
    padding-top: 20px;
    padding-bottom:15px;
    height: 50px;
    width: 100%;
    text-align: center;
  }

  .content {
    width: 80%;
    margin: auto;
  }

</style>
